﻿using System;
using AutoMapper;
using H2.NET.Common;
using H2.NET.Data.Common;
using H2.NET.Web.Management.Config.Service;
using H2.NET.Web.Pages.SMD.Dto;
using H2.NET.Web.Pages.SMD.Model;
using H2.NET.Web.Workflow.Models;
using System.Collections.Generic;
using H2.NET.Web.Workflow.Helper;
using System.Data;
using System.Linq;

namespace H2.NET.Web.Pages.SMD.Service
{
    public class ContractService
    {
        //序列化合同Dto数据（合同和设备一对多）
        public static GridData<StoreContractDto> SearchContractDto(int page, int pageSize, string orderby, List<Condition> condition, string storeIds, string taskid = "")
        {
            // 条件
            string whereStr = " where 1=1";
            
            if (condition.Any())
            {
                var cd = condition.First();
                whereStr = " where s.AuthID like '%" + cd.value + "%'";
            }

            if (storeIds != "")
            {
                whereStr += " AND c.ContractID not in (" + storeIds + ")";
            }
            if (!string.IsNullOrEmpty(taskid))
            {
                var taskapi = new TaskAPI(taskid);
                var region = taskapi.GetVariableBySingleValue("Region");
                if (!string.IsNullOrEmpty(region))
                {
                    whereStr += " and s.region='" + region.Trim() + "'";
                }
                var province = taskapi.GetVariableBySingleValue("Province");
                if (!string.IsNullOrEmpty(province))
                {
                    whereStr += " and s.province='" + province.Trim() + "'";
                }
                var channel = taskapi.GetVariableBySingleValue("Channel");
                if (!string.IsNullOrEmpty(channel))
                {
                    var channel_cn = channel.Trim() == "DULUX" ? "多乐士" : "来威";
                    whereStr += " and s.channel='" + channel_cn + "'";
                }
            }

            // 总数
            string sqlStr = "select count(1) from t_smd_contract  c join t_smd_store s on c.storeid = s.storeid ";
            int count = Utils.ObjToInt(Storage.Context3.ExecuteScalar(new Command(sqlStr + whereStr)), 0);

            // 结果集
            var list = new List<StoreContractDto>();
            sqlStr = "select storetype,StoreID,authid from t_smd_store  s " + whereStr + " and  ((StoreID in (select StoreID from t_smd_Contract)) or (StoreID in (select StoreID from t_smd_ContractDevice)) )";

            if (string.IsNullOrEmpty(orderby))
            {
                orderby = "storeid desc";
            }
            sqlStr = string.Format(";with temp as(\r\n" +
                "	select row_number() over(order by sub.{3}) as rownum, sub.* from ({0}) sub\r\n)\r\n" +
                "select * from temp where rownum between {1} and {2}", sqlStr, pageSize * (page - 1) + 1, pageSize * page, orderby);

            using (var reader = Storage.Context3.ExecuteReader(new Command(sqlStr)))
            {
                while (reader.Read())
                {
                    ContractDto contractDto = Mapper.DynamicMap<ContractDto>(reader);
                    var storeContract = Mapper.DynamicMap<StoreContractDto>(reader);
                    
                    list.Add(storeContract);
                }
            }

            foreach (StoreContractDto contractDto in list)
            {
                var contract = ContractService.GetContractByStoreID(contractDto.StoreID);
                Mapper.CreateMap<t_smd_Contract, ContractDto>();
                var storeContractDto = Mapper.Map<t_smd_Contract, ContractDto>(contract);
                contractDto.contract = storeContractDto;
                string dsql = "select a.* from t_smd_ContractDevice a where storeid = " + contractDto.StoreID;
                List<ContractDeviceDto> devices = new List<ContractDeviceDto>();

                using (var dReader = Storage.Context3.ExecuteReader(new Command(dsql)))
                {
                    while (dReader.Read())
                    {
                        ContractDeviceDto device = Mapper.DynamicMap<ContractDeviceDto>(dReader);
                        devices.Add(device);
                    }
                }

                contractDto.devices = devices;
            }

            return new GridData<StoreContractDto>(list, count);
        }

        //根据storeid找合同
        public static t_smd_Contract GetContractByStoreID(int storeID)
        {
            return (t_smd_Contract._StoreID == storeID).ListFirst<t_smd_Contract>(Storage.Context3);
        }
        public static t_smd_Contract GetContractByID(int contractID)
        {
            return (t_smd_Contract._ContractID == contractID).ListFirst<t_smd_Contract>(Storage.Context3);
        }
        public static t_smd_ContractDevice GetContractDeviceByID(int contractDeviceID)
        {
            return (t_smd_ContractDevice._ContractDeviceID == contractDeviceID).ListFirst<t_smd_ContractDevice>(Storage.Context3);
        }

        public static t_smd_Contract_Cancel GetContractCancel(t_smd_Contract contract)
        {
            var contractCancel = new t_smd_Contract_Cancel
            {
                AuthID = contract.AuthID,
                StoreID = contract.StoreID,
                ContractArchive = contract.ContractArchive,
                StoreCancelContractSN = "1306A",
                StoreCancelContractType = "合同终止及三方转移合同",
                StoreCancelContractBeginDate = DateTime.Now,
                StoreCancelNature ="新签",
                StoreCancelAffiliation = "上海",
                ToStoreCancelEms = contract.ToStoreEms,
                StoreCancelNotSignReason = contract.StoreNotSignReason,
                StoreCancelParty = "阿克苏诺贝尔太古漆油（上海）有限公司",
                StoreCancelCopies = contract.StoreCopies,
                StoreCancelFileNO = contract.StoreFileNO,
                StoreCancelExpressDate = contract.StoreExpressDate,
                StoreCancelEms = contract.StoreEms,
                StoreCancelFinance = contract.StoreFinance,
                StoreCancelArchive = contract.StoreArchive,
                StoreCancelRegionReceive = contract.StoreRegionReceive
            };
            return contractCancel;

        }

        public static t_smd_Contract_Cancel GetOldContract(t_smd_Contract contract)
        {
            var contractCancel = new t_smd_Contract_Cancel
            {
                AuthID = contract.AuthID,
                StoreID = contract.StoreID,
                ContractArchive = contract.ContractArchive,
                StoreCancelContractSN = contract.StoreContractSN,
                StoreCancelContractType = contract.StoreContractType,
                StoreCancelContractBeginDate = contract.StoreContractBeginDate,
                StoreCancelNature = contract.StoreNature,
                StoreCancelAffiliation = contract.StoreAffiliation,
                ToStoreCancelEms = contract.ToStoreEms,
                StoreCancelNotSignReason = contract.StoreNotSignReason,
                StoreCancelParty = contract.StoreParty,
                StoreCancelCopies = contract.StoreCopies,
                StoreCancelFileNO = contract.StoreFileNO,
                StoreCancelExpressDate = contract.StoreExpressDate,
                StoreCancelEms = contract.StoreEms,
                StoreCancelFinance = contract.StoreFinance,
                StoreCancelArchive = contract.StoreArchive,
                StoreCancelRegionReceive = contract.StoreRegionReceive
            };
            return contractCancel;

        }

        public static t_smd_Contract_Cancel GetContractCancelByStoreID(int storeID)
        {
            return (t_smd_Contract_Cancel._StoreID == storeID).ListFirst<t_smd_Contract_Cancel>(Storage.Context3, "ContractCancelID desc");
        }

        public static t_smd_Contract GetNewContract(t_smd_Contract contract,bool xn,string storetype = "")
        {
            contract.ContractArchive = null;
            
            contract.StoreContractSN = "1401A";
            contract.StoreContractType = "多乐士专卖店店铺合同";
            contract.StoreContractBeginDate = DateTime.Now;
            contract.StoreNature = xn?"虚拟合同(此合同可看做没签合同)":"新签";
            contract.StoreAffiliation = "上海";
            contract.ToStoreEms = null;
            contract.StoreNotSignReason = null;
            contract.StoreParty = "阿克苏诺贝尔太古漆油（上海）有限公司";
            contract.StoreCopies = null;
            contract.StoreFileNO = null;
            contract.StoreExpressDate = null;
            contract.StoreEms = null;
            contract.StoreFinance = null;
            contract.StoreArchive = null;
            contract.StoreRegionReceive = null;

            return contract;
        }

        public static t_smd_Contract_Cancel getCotractCancelByDeviceID(int storeid)
        {
            return
                (t_smd_Contract_Cancel._StoreID == storeid).ListFirst<t_smd_Contract_Cancel>(
                    Storage.Context3, "ContractCancelID desc");
        }

    }
}